package com.ytjj.quartz.service;

import com.alibaba.fastjson.JSONObject;
import com.ytjj.qmyx.mall.mapper.ChannelMapper;
import com.ytjj.qmyx.mall.mapper.ProductActivityMapper;
import com.ytjj.qmyx.mall.mapper.ProductActivityMatchingMapper;
import com.ytjj.qmyx.mall.mapper.ProductMatchingMapper;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.users.model.UsersActive;
import com.ytjj.quartz.constants.PayStatisticsConstant;
import com.ytjj.quartz.dao.OrdersDao;
import com.ytjj.quartz.dao.PayStatisticsDao;
import com.ytjj.quartz.dao.UsersDao;
import com.ytjj.quartz.model.PayStatistics;
import com.ytjj.quartz.model.PayStatisticsRequest;
import com.ytjj.quartz.model.PayStatisticsResponse;
import com.ytjj.quartz.model.StatisticsUserResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;

/**
 * @Description 支付统计
 * @ClassName PayStatisticsService
 *
 *
 * @Version 1.0
 **/

@Service
@Slf4j
public class PayStatisticsService {

    @Resource
    private UsersDao usersDao;
    @Resource
    private OrdersDao ordersDao;
    @Resource
    private PayStatisticsDao payStatisticsDao;
    @Resource
    private ProductMatchingMapper productMatchingMapper;
    @Resource
    private ProductActivityMapper productActivityMapper;
    @Resource
    private ProductActivityMatchingMapper productActivityMatchingMapper;
    @Resource
    private ChannelMapper channelMapper;

    /**
     * 统计每日支付信息
     */
    public void addPayStatisticsInfo(String startTime, String endTime) {

        // 定于一个枚举 分平台
        // 遍历枚举 取出每一个平台的渠道
        // 运算每一个渠道数据
        /**
         * 活跃人数
         */
        List<UsersAnalysis> activeUserList = usersDao.getActiveUser(startTime, endTime, PayStatisticsConstant.PLATFORM_ANDROID);
        if(activeUserList == null) {
            activeUserList = new ArrayList<>();
        }
        // h5
        List<UsersAnalysis> h5ActiveUser = usersDao.getActiveUser(startTime, endTime, PayStatisticsConstant.PLATFORM_h5);
        if(h5ActiveUser == null) {
            h5ActiveUser = new ArrayList<>();
        }
        List<UsersAnalysis> activeUserNoChannel = Optional.ofNullable(activeUserList)
                .orElseGet(() -> Collections.emptyList())
                .stream().filter(item -> Strings.isEmpty(item.getChannel()))
                .collect(Collectors.toList());
        // android
        Map<String, Long> activeUserMap = Optional.ofNullable(activeUserList.stream()
                .filter(item -> Strings.isNotEmpty(item.getChannel()))
                .collect(groupingBy(UsersAnalysis::getChannel, counting()))).orElseGet(() -> Collections.emptyMap());
        // h5
        Map<String, Long> h5ActiveUserMap = Optional.ofNullable(h5ActiveUser.stream()
                .filter(item -> Strings.isNotEmpty(item.getChannel()))
                .collect(groupingBy(UsersAnalysis::getChannel, counting()))).orElseGet(() -> Collections.emptyMap());

        // ios活跃人数
        List<UsersAnalysis> activeUserIosList = Optional.ofNullable(usersDao.getActiveUser(startTime, endTime, PayStatisticsConstant.PLATFORM_IOS))
                .orElseGet(() -> Collections.emptyList());
        // 小程序
        List<UsersAnalysis> activeUserWeappList = Optional.ofNullable(usersDao.getActiveUser(startTime, endTime, PayStatisticsConstant.PLATFORM_WEAPP))
                .orElseGet(() -> Collections.emptyList());

        /**
         * 首次购买人数
         */

        // android
        List<Orders> androidFirstBuyNumList = ordersDao.getFirstBuyNum(startTime, endTime, PayStatisticsConstant.PLATFORM_ANDROID);
        Map<String, Long> androidFirstBuyNumMap = androidFirstBuyNumList.stream()
                .filter(item -> Strings.isNotEmpty(item.getChannel()))
                .collect(groupingBy(Orders::getChannel, counting()));
        // h5
        List<Orders> h5FirstByNumList = ordersDao.getFirstBuyNum(startTime, endTime, PayStatisticsConstant.PLATFORM_h5);
        Map<String, Long> h5FirstByNumListMap = h5FirstByNumList.stream()
                .filter(item -> Strings.isNotEmpty(item.getChannel()))
                .collect(groupingBy(Orders::getChannel, counting()));
        // weapp
        List<Orders> weappFirstByNumList = ordersDao.getFirstBuyNum(startTime, endTime, PayStatisticsConstant.PLATFORM_WEAPP);
        // ios
        List<Orders> iosFirstByNumList = ordersDao.getFirstBuyNum(startTime, endTime, PayStatisticsConstant.PLATFORM_WEAPP);



        /**
         * 新增人数
         */
        List<StatisticsUserResponse> addUserList = usersDao.getAddUser(startTime, endTime, PayStatisticsConstant.PLATFORM_ANDROID);
        if(addUserList == null) {
            addUserList = new ArrayList<>();
        }
        // h5
        List<StatisticsUserResponse> h5AddUserList = usersDao.getAddUser(startTime, endTime, PayStatisticsConstant.PLATFORM_h5);
        if(h5AddUserList == null) {
            h5AddUserList = new ArrayList<>();
        }
        List<StatisticsUserResponse> addUserNoChannel = Optional.ofNullable(addUserList)
                .orElseGet(() -> Collections.emptyList())
                .stream().filter(item -> Strings.isEmpty(item.getChannel())).collect(Collectors.toList());
        Map<String, Long> addUserMap = Optional.ofNullable(addUserList.stream()
                .filter(item -> Strings.isNotEmpty(item.getChannel()))
                .collect(groupingBy(StatisticsUserResponse::getChannel, counting()))).orElseGet(() -> Collections.emptyMap());
        // h5
        Map<String, Long> h5AddUserMap = Optional.ofNullable(h5AddUserList.stream()
                .filter(item -> Strings.isNotEmpty(item.getChannel()))
                .collect(groupingBy(StatisticsUserResponse::getChannel, counting()))).orElseGet(() -> Collections.emptyMap());
        List<StatisticsUserResponse> addUserIosList = Optional.ofNullable(usersDao.getAddUser(startTime, endTime, PayStatisticsConstant.PLATFORM_IOS))
                .orElseGet(() -> Collections.emptyList());
        List<StatisticsUserResponse> addUserWeappList = Optional.ofNullable(usersDao.getAddUser(startTime, endTime, PayStatisticsConstant.PLATFORM_WEAPP))
                .orElseGet(() -> Collections.emptyList());

        /**
         * 用户点击地址数
         */
        // android
        List<ExtraAnalysis> addressClickCount = usersDao.getAddressClickCount(startTime, endTime, PayStatisticsConstant.PLATFORM_ANDROID);
        if(addressClickCount == null) {
            addressClickCount = new ArrayList<>();
        }
        Map<String, Long> androidAddressClickCountMap = Optional.ofNullable(addressClickCount
                .stream()
                .filter(item -> Strings.isNotEmpty(item.getChannel()))
                .collect(groupingBy(ExtraAnalysis::getChannel, counting()))).orElseGet(() -> Collections.emptyMap());

        // h5
        List<ExtraAnalysis> h5AddressClickCount = usersDao.getAddressClickCount(startTime, endTime, PayStatisticsConstant.PLATFORM_h5);
        if(h5AddressClickCount == null) {
            h5AddressClickCount = new ArrayList<>();
        }
        Map<String, Long> h5AddressClickCountMap = Optional.ofNullable(h5AddressClickCount
                .stream()
                .filter(item -> Strings.isNotEmpty(item.getChannel()))
                .collect(groupingBy(ExtraAnalysis::getChannel, counting()))).orElseGet(() -> Collections.emptyMap());


        /**
         * 订单数
         */
        List<PayStatisticsResponse> ordersCount = ordersDao.getOrdersCount(startTime, endTime, PayStatisticsConstant.PLATFORM_ANDROID);

        // h5
        List<PayStatisticsResponse> h5OrdersCount = ordersDao.getOrdersCount(startTime, endTime, PayStatisticsConstant.PLATFORM_h5);

        List<PayStatisticsResponse> ordersNoChannel = Optional.ofNullable(ordersCount)
                .orElseGet(() -> Collections.emptyList())
                .stream().filter(item -> Strings.isEmpty(item.getChannel())).collect(Collectors.toList());
        Map<String, Long> androidOrdersMap = Optional.ofNullable(ordersCount.stream()
                .filter(item -> Strings.isNotEmpty(item.getChannel()))
                .collect(groupingBy(PayStatisticsResponse::getChannel, counting()))).orElseGet(() -> Collections.emptyMap());
        // h5
        Map<String, Long> h5OrdersMap = Optional.ofNullable(h5OrdersCount.stream()
                .filter(item -> Strings.isNotEmpty(item.getChannel()))
                .collect(groupingBy(PayStatisticsResponse::getChannel, counting()))).orElseGet(() -> Collections.emptyMap());
        List<PayStatisticsResponse> ordersIosCount = Optional.ofNullable(ordersDao.getOrdersCount(startTime, endTime, PayStatisticsConstant.PLATFORM_IOS))
                .orElseGet(() -> Collections.emptyList());
        List<PayStatisticsResponse> ordersWeappCount = Optional.ofNullable(ordersDao.getOrdersCount(startTime, endTime, PayStatisticsConstant.PLATFORM_WEAPP))
                .orElseGet(() -> Collections.emptyList());


        /**
         * 实际订单数
         */
        // android
        List<PayStatisticsResponse> realOrdersCount = ordersDao.getRealOrdersCount(startTime, endTime, PayStatisticsConstant.PLATFORM_ANDROID);
        Map<String, Long> androidRealOrdersMap = Optional.ofNullable(realOrdersCount.stream()
                .filter(item -> Strings.isNotEmpty(item.getChannel()))
                .collect(groupingBy(PayStatisticsResponse::getChannel, counting()))).orElseGet(() -> Collections.emptyMap());
        // h5
        List<PayStatisticsResponse> realH5OrdersCount = ordersDao.getRealOrdersCount(startTime, endTime, PayStatisticsConstant.PLATFORM_h5);
        Map<String, Long> h5RealOrdersMap = Optional.ofNullable(realH5OrdersCount.stream()
                .filter(item -> Strings.isNotEmpty(item.getChannel()))
                .collect(groupingBy(PayStatisticsResponse::getChannel, counting()))).orElseGet(() -> Collections.emptyMap());
        /**
         *  支付订单数
         */
        List<PayStatisticsResponse> payOrdersCount = ordersDao.getPayOrdersCount(startTime, endTime, PayStatisticsConstant.PLATFORM_ANDROID);
        if(payOrdersCount == null) {
            payOrdersCount = new ArrayList<>();
        }
        // h5
        List<PayStatisticsResponse> h5PayOrdersCount = ordersDao.getPayOrdersCount(startTime, endTime, PayStatisticsConstant.PLATFORM_h5);
        if(h5PayOrdersCount == null) {
            h5PayOrdersCount = new ArrayList<>();
        }
        List<PayStatisticsResponse> payOrdersNoChannel = Optional.ofNullable(payOrdersCount)
                .orElseGet(() -> Collections.emptyList())
                .stream().filter(item -> Strings.isEmpty(item.getChannel())).collect(Collectors.toList());
        Map<String, Long> androidPayOrderMap = Optional.ofNullable(payOrdersCount.stream()
                .filter(item -> Strings.isNotEmpty(item.getChannel()))
                .collect(groupingBy(PayStatisticsResponse::getChannel, counting()))).orElseGet(() -> Collections.emptyMap());
        // h5
        Map<String, Long> h5PayOrderMap = Optional.ofNullable(h5PayOrdersCount.stream()
                .filter(item -> Strings.isNotEmpty(item.getChannel()))
                .collect(groupingBy(PayStatisticsResponse::getChannel, counting()))).orElseGet(() -> Collections.emptyMap());
        List<PayStatisticsResponse> payOrdersIosCount = Optional.ofNullable(ordersDao.getPayOrdersCount(startTime, endTime, PayStatisticsConstant.PLATFORM_IOS))
                .orElseGet(() -> Collections.emptyList());
        List<PayStatisticsResponse> payOrdersWeappCount = Optional.ofNullable(ordersDao.getPayOrdersCount(startTime, endTime, PayStatisticsConstant.PLATFORM_WEAPP))
                .orElseGet(() -> Collections.emptyList());


        /**
         * 支付金额
          */

        List<PayStatisticsResponse> payOrdersAmount = ordersDao.getPayOrdersAmount(startTime, endTime, PayStatisticsConstant.PLATFORM_ANDROID);
        List<PayStatisticsResponse> noChannelPayOrdersAmount = ordersDao.getNoChannelPayOrdersAmount(startTime, endTime, PayStatisticsConstant.PLATFORM_ANDROID);
        List<PayStatisticsResponse> payOrdersIosAmount = ordersDao.getPayOrdersAmount(startTime, endTime, PayStatisticsConstant.PLATFORM_IOS);
        List<PayStatisticsResponse> payOrdersWeappAmount = ordersDao.getPayOrdersAmount(startTime, endTime, PayStatisticsConstant.PLATFORM_WEAPP);
        // h5
        List<PayStatisticsResponse> payOrdersH5Amount = ordersDao.getPayOrdersAmount(startTime, endTime, PayStatisticsConstant.PLATFORM_h5);


        /**
         * 成本
         */
        List<PayStatisticsResponse> ordersCostAmount = ordersDao.getOrdersCostAmount(startTime, endTime, PayStatisticsConstant.PLATFORM_ANDROID);
        List<PayStatisticsResponse> noChannelOrdersCostAmount = ordersDao.getNoChanneOrdersCostAmount(startTime, endTime, PayStatisticsConstant.PLATFORM_ANDROID);
        List<PayStatisticsResponse> ordersCostIosAmount = ordersDao.getOrdersCostAmount(startTime, endTime, PayStatisticsConstant.PLATFORM_IOS);
        List<PayStatisticsResponse> ordersCostWeappAmount = ordersDao.getOrdersCostAmount(startTime, endTime, PayStatisticsConstant.PLATFORM_WEAPP);
        // h5
        List<PayStatisticsResponse> ordersCostH5Amount = ordersDao.getOrdersCostAmount(startTime, endTime, PayStatisticsConstant.PLATFORM_h5);


        /**
         * android各个渠道统计
         */
        /*Supplier<Stream<String>> stringList = () -> Stream.of("360mobileHelper", "baidu", "cpd", "huawei", "meizu", "oppo", "uc", "vivo", "xiaomi", "yyb", "dy", "dsp",
                "qqbrowse-dsp", "sougou-mobile", "sougou");*/
        ChannelExample channelExample = new ChannelExample();
        channelExample.createCriteria()
                .andPlatformEqualTo("android")
                .andStatusEqualTo((byte) 1);
        List<Channel> channelList = channelMapper.selectByExample(channelExample);
        List<String> channelStrList = null;
        if (channelList.size() > 0) {
            channelStrList = channelList.stream()
                    .filter(Objects::nonNull)
                    .map(Channel::getChannel)
                    .collect(Collectors.toList());
        }
        channelStrList.forEach(channel -> {
            // 活跃用户
            Integer daus = 0;
            // 新增用户
            Integer addUser = 0;
            // 订单数
            Integer orderNum = 0;
            // 实际订单数
            Integer realOrderNum = 0;
            // 支付订单数
            Integer payNum = 0;
            // 点击填写地址数
            Integer addressClickNum = 0;
            // 首次购买数
            Integer firstBuyNum = 0;
            if (activeUserMap.containsKey(channel)) {
                daus = activeUserMap.get(channel).intValue();
            }
            if (addUserMap.containsKey(channel)) {
                addUser = addUserMap.get(channel).intValue();
            }
            if (androidOrdersMap.containsKey(channel)) {
                orderNum = androidOrdersMap.get(channel).intValue();
            }
            if(androidRealOrdersMap.containsKey(channel)) {
                realOrderNum = androidRealOrdersMap.get(channel).intValue();
            }
            if (androidPayOrderMap.containsKey(channel)) {
                payNum = androidPayOrderMap.get(channel).intValue();
            }
            if(androidAddressClickCountMap.containsKey(channel)) {
                addressClickNum = androidAddressClickCountMap.get(channel).intValue();
            }
            if(androidFirstBuyNumMap.containsKey(channel)) {
                firstBuyNum = androidFirstBuyNumMap.get(channel).intValue();
            }
            // 支付金额
            BigDecimal payMoney = Optional.ofNullable(payOrdersAmount.stream()
                    .filter(item -> channel.equals(item.getChannel()))
                    .map(PayStatisticsResponse::getProductPrice)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)).orElseGet(() -> BigDecimal.ZERO);
            // 成本总金额
            BigDecimal costMoney = Optional.ofNullable(ordersCostAmount.stream()
                    .filter(item -> channel.equals(item.getChannel()))
                    .map(PayStatisticsResponse::getCostPrice)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)).orElseGet(() -> BigDecimal.ZERO);
            // 支付率  支付成功单数/下单数
            BigDecimal payRation = BigDecimal.ZERO;
            // 订单率  订单数/日活
            BigDecimal orderRatio = BigDecimal.ZERO;
            // 客单 支付金额/支付数
            BigDecimal customerRatio = BigDecimal.ZERO;
            if (payNum != 0) {
                payRation = BigDecimal.valueOf(payNum.longValue()).divide(BigDecimal.valueOf(orderNum.longValue()), 4, BigDecimal.ROUND_DOWN);
            }
            if(daus != 0) {
                orderRatio = BigDecimal.valueOf(realOrderNum.longValue()).divide(BigDecimal.valueOf(daus.longValue()), 4, BigDecimal.ROUND_DOWN);
            }
            if(payNum != 0) {
                customerRatio = payMoney.divide(BigDecimal.valueOf(payNum.longValue()), 4, BigDecimal.ROUND_DOWN);
            }
            // 激活人数
            List<UsersActive> usersActiveList = Optional.ofNullable(usersDao.getUsersActive(PayStatisticsConstant.PLATFORM_ANDROID, channel, startTime, endTime))
                    .orElseGet(() -> Collections.emptyList());
            // app统计
            PayStatistics appPayStatistics = new PayStatistics()
                    .setDaus(daus)
                    .setNewUser(addUser)
                    .setOrderNum(orderNum)
                    .setPayNum(payNum)
                    .setPayRatio(payRation + "")
                    .setPayMoney(payMoney)
                    .setCostMoney(costMoney)
                    .setActiveUser(usersActiveList.size())
                    .setProfit(payMoney.subtract(costMoney).setScale(2, BigDecimal.ROUND_DOWN))
                    .setSource(PayStatisticsConstant.PLATFORM_ANDROID)
                    .setChannel(channel)
                    .setRealOrderNum(realOrderNum)
                    .setOrderRatio(orderRatio + "")
                    .setCustomerRatio(customerRatio + "")
                    .setFirstBuyNum(firstBuyNum)
                    .setAddressClickNum(addressClickNum)
                    .setCreateTime(new Date());
            log.info("app统计", JSONObject.toJSONString(appPayStatistics));
            PayStatisticsRequest payStatisticsRequest = new PayStatisticsRequest();
            payStatisticsRequest.setChannel(appPayStatistics.getChannel());
            payStatisticsRequest.setCreateTime(appPayStatistics.getCreateTime());
            payStatisticsRequest.setSource(appPayStatistics.getSource());
            payStatisticsRequest.setStartTime(startTime);
            payStatisticsRequest.setEndTime(endTime);
            BeanUtils.copyProperties(appPayStatistics, payStatisticsRequest);
            PayStatistics payStatistics = payStatisticsDao.queryPayStatistics(payStatisticsRequest);
            if (payStatistics == null) {
                payStatisticsDao.insertPayStatistics(appPayStatistics);
            } else {
                payStatisticsRequest.setRecordTime(new Date());
                payStatisticsRequest.setId(payStatistics.getId());
                payStatisticsDao.updatePayStatistic(payStatisticsRequest);
            }
        });


        /**
         * h5各个渠道统计
         */
        ChannelExample h5ChannelExample = new ChannelExample();
        h5ChannelExample.createCriteria()
                .andPlatformEqualTo("h5")
                .andStatusEqualTo((byte) 1);
        List<Channel> h5ChannelList = channelMapper.selectByExample(h5ChannelExample);
        List<String> h5ChannelStrList = null;
        if (h5ChannelList.size() > 0) {
            h5ChannelStrList = h5ChannelList.stream()
                    .filter(Objects::nonNull)
                    .map(Channel::getChannel)
                    .collect(Collectors.toList());
        }
        h5ChannelStrList.forEach(channel -> {
            // 活跃用户
            Integer daus = 0;
            // 新增用户
            Integer addUser = 0;
            // 订单数
            Integer orderNum = 0;
            // 实际订单数
            Integer realOrderNum = 0;
            // 支付订单数
            Integer payNum = 0;
            // 点击填写地址数
            Integer addressClickNum = 0;
            // 首次购买数
            Integer firstBuyNum = 0;
            if (h5ActiveUserMap.containsKey(channel)) {
                daus = h5ActiveUserMap.get(channel).intValue();
            }
            if (h5AddUserMap.containsKey(channel)) {
                addUser = h5AddUserMap.get(channel).intValue();
            }
            if (h5OrdersMap.containsKey(channel)) {
                orderNum = h5OrdersMap.get(channel).intValue();
            }
            if(h5RealOrdersMap.containsKey(channel)) {
                realOrderNum = h5RealOrdersMap.get(channel).intValue();
            }
            if (h5PayOrderMap.containsKey(channel)) {
                payNum = h5PayOrderMap.get(channel).intValue();
            }
            if(h5AddressClickCountMap.containsKey(channel)) {
                addressClickNum = h5AddressClickCountMap.get(channel).intValue();
            }
            if(h5FirstByNumListMap.containsKey(channel)) {
                firstBuyNum = h5FirstByNumListMap.get(channel).intValue();
            }
            // 支付金额
            BigDecimal payMoney = Optional.ofNullable(payOrdersH5Amount.stream()
                    .filter(item -> channel.equals(item.getChannel()))
                    .map(PayStatisticsResponse::getProductPrice)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)).orElseGet(() -> BigDecimal.ZERO);
            // 成本总金额
            BigDecimal costMoney = Optional.ofNullable(ordersCostH5Amount.stream()
                    .filter(item -> channel.equals(item.getChannel()))
                    .map(PayStatisticsResponse::getCostPrice)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)).orElseGet(() -> BigDecimal.ZERO);
            // 支付率  支付成功单数/下单数
            BigDecimal payRation = BigDecimal.ZERO;
            // 订单率  订单数/日活
            BigDecimal orderRatio = BigDecimal.ZERO;
            // 客单 支付金额/支付数
            BigDecimal customerRatio = BigDecimal.ZERO;
            if (payNum != 0) {
                payRation = BigDecimal.valueOf(payNum.longValue()).divide(BigDecimal.valueOf(orderNum.longValue()), 4, BigDecimal.ROUND_DOWN);
            }
            if(daus != 0) {
                orderRatio = BigDecimal.valueOf(realOrderNum.longValue()).divide(BigDecimal.valueOf(daus.longValue()), 4, BigDecimal.ROUND_DOWN);
            }
            if(payNum != 0) {
                customerRatio = payMoney.divide(BigDecimal.valueOf(payNum.longValue()), 4, BigDecimal.ROUND_HALF_UP);
            }
            // 激活人数
            List<UsersActive> usersActiveList = Optional.ofNullable(usersDao.getUsersActive(PayStatisticsConstant.PLATFORM_h5, channel, startTime, endTime))
                    .orElseGet(() -> Collections.emptyList());
            // h5统计
            PayStatistics h5PayStatistics = new PayStatistics()
                    .setDaus(daus)
                    .setNewUser(addUser)
                    .setOrderNum(orderNum)
                    .setPayNum(payNum)
                    .setPayRatio(payRation + "")
                    .setPayMoney(payMoney)
                    .setCostMoney(costMoney)
                    .setActiveUser(usersActiveList.size())
                    .setProfit(payMoney.subtract(costMoney).setScale(2, BigDecimal.ROUND_DOWN))
                    .setSource(PayStatisticsConstant.PLATFORM_h5)
                    .setChannel(channel)
                    .setRealOrderNum(realOrderNum)
                    .setOrderRatio(orderRatio + "")
                    .setCustomerRatio(customerRatio + "")
                    .setFirstBuyNum(firstBuyNum)
                    .setAddressClickNum(addressClickNum)
                    .setCreateTime(new Date());
            log.info("h5统计", JSONObject.toJSONString(h5PayStatistics));
            PayStatisticsRequest payStatisticsRequest = new PayStatisticsRequest();
            payStatisticsRequest.setChannel(h5PayStatistics.getChannel());
            payStatisticsRequest.setCreateTime(h5PayStatistics.getCreateTime());
            payStatisticsRequest.setSource(h5PayStatistics.getSource());
            payStatisticsRequest.setStartTime(startTime);
            payStatisticsRequest.setEndTime(endTime);
            BeanUtils.copyProperties(h5PayStatistics, payStatisticsRequest);
            PayStatistics payStatistics = payStatisticsDao.queryPayStatistics(payStatisticsRequest);
            if (payStatistics == null) {
                payStatisticsDao.insertPayStatistics(h5PayStatistics);
            } else {
                payStatisticsRequest.setRecordTime(new Date());
                payStatisticsRequest.setId(payStatistics.getId());
                payStatisticsDao.updatePayStatistic(payStatisticsRequest);
            }
        });

//        /**
//         * android 汇总
//         */
//
//        List<UsersActive> androidUsersActiveList = Optional.ofNullable(usersDao.getUsersActive(PayStatisticsConstant.PLATFORM_ANDROID, null, startTime, endTime))
//                .orElseGet(() -> Collections.emptyList());
//        // 支付金额
//        BigDecimal androidPayMoney = Optional.ofNullable(payOrdersAmount.stream()
//                .map(PayStatisticsResponse::getProductPrice)
//                .reduce(BigDecimal.ZERO, BigDecimal::add)).orElseGet(() -> (BigDecimal.ZERO));
//        // 成本总金额
//        BigDecimal androidCostMoney = Optional.ofNullable(ordersCostAmount.stream()
//                .map(PayStatisticsResponse::getCostPrice)
//                .reduce(BigDecimal.ZERO, BigDecimal::add)).orElseGet(() -> (BigDecimal.ZERO));
//        // 支付率  支付成功单数/下单数
//        BigDecimal androidPayRation = BigDecimal.ZERO;
//        // 订单率  订单数/日活
//        BigDecimal androidOrderRatio = BigDecimal.ZERO;
//        // 客单 支付金额/支付数
//        BigDecimal androidCustomerRatio = BigDecimal.ZERO;
//        if (ordersCount.size() != 0) {
//            Integer payOrderNo = payOrdersCount.size();
//            Integer ordersNo = ordersCount.size();
//            androidPayRation = BigDecimal.valueOf(payOrderNo).divide(BigDecimal.valueOf(ordersNo), 4, BigDecimal.ROUND_DOWN);
//        }
//        // 订单率 订单数/日活
//        if(activeUserList.size() != 0) {
//            Integer ordersNo = ordersCount.size();
//            Integer daus = activeUserList.size();
//            androidOrderRatio = BigDecimal.valueOf(ordersNo.longValue()).divide(BigDecimal.valueOf(daus.longValue()), 4, BigDecimal.ROUND_DOWN);
//        }
//        // 客单率 支付金额/支付数
//        if(payOrdersCount.size() != 0) {
//            Integer payCount = payOrdersCount.size();
//            androidCustomerRatio = androidPayMoney.divide(BigDecimal.valueOf(payCount.longValue()), 4, BigDecimal.ROUND_DOWN);
//        }
//        // 渠道统计
//        ChannelStatistics channelStatistics = new ChannelStatistics();
//        channelStatistics.setDaus(activeUserList.size());
//        channelStatistics.setNewUser(addUserList.size());
//        channelStatistics.setOrderNum(ordersCount.size());
//        channelStatistics.setPayNum(payOrdersCount.size());
//        channelStatistics.setPayRatio(androidPayRation + "");
//        channelStatistics.setPayMoney(androidPayMoney);
//        channelStatistics.setCostMoney(androidCostMoney);
//        channelStatistics.setActiveUser(androidUsersActiveList.size());
//        channelStatistics.setProfit(androidPayMoney.subtract(androidCostMoney).setScale(2, BigDecimal.ROUND_DOWN));
//        channelStatistics.setSource(PayStatisticsConstant.PLATFORM_ANDROID);
//        channelStatistics.setChannel("全渠道");
//        channelStatistics.setOrderRatio(androidOrderRatio + "");
//        channelStatistics.setCustomerRatio(androidCustomerRatio + "");
//        channelStatistics.setAddressClickNum(addressClickCount.size());
//        channelStatistics.setFirstBuyNum(androidFirstBuyNumList.size());
//        channelStatistics.setCreateTime(new Date());
//
//        log.info("android全渠道 {}", JSONObject.toJSONString(channelStatistics));
//        ChannelStatisticsRequest channelStatisticsRequest = new ChannelStatisticsRequest();
//        channelStatisticsRequest.setChannel(channelStatistics.getChannel());
//        channelStatisticsRequest.setCreateTime(channelStatistics.getCreateTime());
//        channelStatisticsRequest.setSource(channelStatistics.getSource());
//        channelStatisticsRequest.setStartTime(startTime);
//        channelStatisticsRequest.setEndTime(endTime);
//        BeanUtils.copyProperties(channelStatistics, channelStatisticsRequest);
//        ChannelStatistics androidChannelStatistics = payStatisticsDao.queryChannelStatistics(channelStatisticsRequest);
//        if (androidChannelStatistics == null) {
//            payStatisticsDao.insertChannelStatistics(channelStatistics);
//        } else {
//            channelStatisticsRequest.setId(androidChannelStatistics.getId());
//            channelStatisticsRequest.setRecordTime(new Date());
//            payStatisticsDao.updateChannelStatistic(channelStatisticsRequest);
//        }
//
//
//        /**
//         * 小程序
//         */
//        // 支付金额
//        BigDecimal payWeappMoney = Optional.ofNullable(payOrdersWeappAmount.stream()
//                .map(PayStatisticsResponse::getProductPrice)
//                .reduce(BigDecimal.ZERO, BigDecimal::add)).orElseGet(() -> (BigDecimal.ZERO));
//        // 成本总金额
//        BigDecimal costWeappMoney = Optional.ofNullable(ordersCostWeappAmount.stream()
//                .map(PayStatisticsResponse::getCostPrice)
//                .reduce(BigDecimal.ZERO, BigDecimal::add)).orElseGet(() -> (BigDecimal.ZERO));
//        // 支付率  支付成功单数/下单数
//        BigDecimal payWeappRation = BigDecimal.ZERO;
//        // 订单率  订单数/日活
//        BigDecimal weappOrderRatio = BigDecimal.ZERO;
//        // 客单 支付金额/支付数
//        BigDecimal weappCustomerRatio = BigDecimal.ZERO;
//        if (payOrdersWeappCount.size() != 0) {
//            Integer payCount = payOrdersWeappCount.size();
//            Integer orderNum = ordersWeappCount.size();
//            payWeappRation = BigDecimal.valueOf(payCount.longValue()).divide(BigDecimal.valueOf(orderNum.longValue()), 4, BigDecimal.ROUND_DOWN);
//        }
//        // 订单率 订单数/日活
//        if(activeUserWeappList.size() != 0) {
//            Integer orderCount = ordersWeappCount.size();
//            Integer daus = activeUserWeappList.size();
//            weappOrderRatio = BigDecimal.valueOf(orderCount.longValue()).divide(BigDecimal.valueOf(daus.longValue()), 4, BigDecimal.ROUND_DOWN);
//        }
//        // 客单率 支付金额/支付数
//        if(payOrdersWeappCount.size() != 0) {
//            Integer payCount = payOrdersWeappCount.size();
//            weappCustomerRatio = payWeappMoney.divide(BigDecimal.valueOf(payCount.longValue()), 4, BigDecimal.ROUND_DOWN);
//        }
//        // 激活用户
//        // 激活人数
//        List<UsersActive> usersActiveList = Optional.ofNullable(usersDao.getUsersActive(PayStatisticsConstant.PLATFORM_WEAPP, null, startTime, endTime))
//                .orElseGet(() -> Collections.emptyList());
//
//        ChannelStatistics weappChannelStatistics = new ChannelStatistics();
//        weappChannelStatistics.setDaus(activeUserWeappList.size());
//        weappChannelStatistics.setNewUser(addUserWeappList.size());
//        weappChannelStatistics.setOrderNum(ordersWeappCount.size());
//        weappChannelStatistics.setPayNum(payOrdersWeappCount.size());
//        weappChannelStatistics.setPayRatio(payWeappRation + "");
//        weappChannelStatistics.setPayMoney(payWeappMoney);
//        weappChannelStatistics.setCostMoney(costWeappMoney);
//        weappChannelStatistics.setProfit(payWeappMoney.subtract(costWeappMoney).setScale(2, BigDecimal.ROUND_DOWN));
//        weappChannelStatistics.setSource(PayStatisticsConstant.PLATFORM_WEAPP);
//        weappChannelStatistics.setChannel(PayStatisticsConstant.PLATFORM_WEAPP);
//        weappChannelStatistics.setActiveUser(usersActiveList.size());
//        weappChannelStatistics.setOrderRatio(weappOrderRatio + "");
//        weappChannelStatistics.setCustomerRatio(weappCustomerRatio + "");
//        weappChannelStatistics.setFirstBuyNum(weappFirstByNumList.size());
//        weappChannelStatistics.setCreateTime(new Date());
//        log.info("小程序 {}", JSONObject.toJSONString(weappChannelStatistics));
//        ChannelStatisticsRequest weappChannelStatisticsRequest = new ChannelStatisticsRequest();
//        weappChannelStatisticsRequest.setChannel(weappChannelStatistics.getChannel());
//        weappChannelStatisticsRequest.setCreateTime(weappChannelStatistics.getCreateTime());
//        weappChannelStatisticsRequest.setSource(weappChannelStatistics.getSource());
//        weappChannelStatisticsRequest.setStartTime(startTime);
//        weappChannelStatisticsRequest.setEndTime(endTime);
//        BeanUtils.copyProperties(weappChannelStatistics, weappChannelStatisticsRequest);
//        ChannelStatistics channelStatistics1 = payStatisticsDao.queryChannelStatistics(weappChannelStatisticsRequest);
//        if (channelStatistics1 == null) {
//            payStatisticsDao.insertChannelStatistics(weappChannelStatistics);
//        } else {
//            weappChannelStatisticsRequest.setId(channelStatistics1.getId());
//            weappChannelStatisticsRequest.setRecordTime(new Date());
//            payStatisticsDao.updateChannelStatistic(weappChannelStatisticsRequest);
//        }
//
//        /**
//         * ios
//         */
//        // 支付金额
//        BigDecimal payIosMoney = Optional.ofNullable(payOrdersIosAmount.stream()
//                .map(PayStatisticsResponse::getProductPrice)
//                .reduce(BigDecimal.ZERO, BigDecimal::add)).orElseGet(() -> (BigDecimal.ZERO));
//        // 成本总金额
//        BigDecimal costIosMoney = Optional.ofNullable(ordersCostIosAmount.stream()
//                .map(PayStatisticsResponse::getCostPrice)
//                .reduce(BigDecimal.ZERO, BigDecimal::add)).orElseGet(() -> (BigDecimal.ZERO));
//        // 激活人数
//        List<UsersActive> iosUsersActiveList = Optional.ofNullable(usersDao.getUsersActive(PayStatisticsConstant.PLATFORM_IOS, null, startTime, endTime))
//                .orElseGet(() -> Collections.emptyList());
//        // 支付率  支付成功单数/下单数
//        BigDecimal payIosRation = BigDecimal.ZERO;
//        // 订单率  订单数/日活
//        BigDecimal iosOrderRatio = BigDecimal.ZERO;
//        // 客单 支付金额/支付数
//        BigDecimal iosCustomerRatio = BigDecimal.ZERO;
//        if (payOrdersIosCount.size() != 0) {
//            Integer payCount = payOrdersIosCount.size();
//            Integer orderNum = ordersIosCount.size();
//            payIosRation = BigDecimal.valueOf(payCount.longValue()).divide(BigDecimal.valueOf(orderNum.longValue()), 4, BigDecimal.ROUND_DOWN);
//        }
//        // 订单率 订单数/日活
//        if(activeUserIosList.size() != 0) {
//            Integer orderCount = payOrdersIosCount.size();
//            Integer daus = activeUserIosList.size();
//            iosOrderRatio = BigDecimal.valueOf(orderCount.longValue()).divide(BigDecimal.valueOf(daus.longValue()), 4, BigDecimal.ROUND_DOWN);
//        }
//        // 客单率 支付金额/支付数
//        if(payOrdersIosCount.size() != 0) {
//            Integer payCount = payOrdersIosCount.size();
//            iosCustomerRatio = payIosMoney.divide(BigDecimal.valueOf(payCount.longValue()), 4, BigDecimal.ROUND_DOWN);
//        }
//        ChannelStatistics iosChannelStatistics = new ChannelStatistics();
//        iosChannelStatistics.setDaus(activeUserIosList.size());
//        iosChannelStatistics.setNewUser(addUserIosList.size());
//        iosChannelStatistics.setOrderNum(ordersIosCount.size());
//        iosChannelStatistics.setPayNum(payOrdersIosCount.size());
//        iosChannelStatistics.setPayRatio(payIosRation + "");
//        iosChannelStatistics.setPayMoney(payIosMoney);
//        iosChannelStatistics.setCostMoney(costIosMoney);
//        iosChannelStatistics.setActiveUser(iosUsersActiveList.size());
//        iosChannelStatistics.setProfit(payIosMoney.subtract(costIosMoney).setScale(2, BigDecimal.ROUND_DOWN));
//        iosChannelStatistics.setSource(PayStatisticsConstant.PLATFORM_IOS);
//        iosChannelStatistics.setChannel(PayStatisticsConstant.PLATFORM_IOS);
//        iosChannelStatistics.setOrderRatio(iosOrderRatio + "");
//        iosChannelStatistics.setCustomerRatio(iosCustomerRatio + "");
//        iosChannelStatistics.setCreateTime(new Date());
//        iosChannelStatistics.setFirstBuyNum(iosFirstByNumList.size());
//        log.info("ios {}", JSONObject.toJSONString(iosChannelStatistics));
//
//        ChannelStatisticsRequest iosChannelStatisticsRequest = new ChannelStatisticsRequest();
//        iosChannelStatisticsRequest.setChannel(iosChannelStatistics.getChannel());
//        iosChannelStatisticsRequest.setCreateTime(iosChannelStatistics.getCreateTime());
//        iosChannelStatisticsRequest.setSource(iosChannelStatistics.getSource());
//        iosChannelStatisticsRequest.setStartTime(startTime);
//        iosChannelStatisticsRequest.setEndTime(endTime);
//        BeanUtils.copyProperties(iosChannelStatistics, iosChannelStatisticsRequest);
//        ChannelStatistics channelStatistics2 = payStatisticsDao.queryChannelStatistics(iosChannelStatisticsRequest);
//        if (channelStatistics2 == null) {
//            payStatisticsDao.insertChannelStatistics(iosChannelStatistics);
//        } else {
//            iosChannelStatisticsRequest.setId(channelStatistics2.getId());
//            iosChannelStatisticsRequest.setRecordTime(new Date());
//            payStatisticsDao.updateChannelStatistic(iosChannelStatisticsRequest);
//        }
    }

    public void activityMatchingRecord() {
        ProductMatchingExample productMatchingExample = new ProductMatchingExample();
        productMatchingExample.createCriteria();
        List<ProductMatching> productMatchingList = productMatchingMapper.selectByExampleWithBLOBs(productMatchingExample);
        for (ProductMatching productMatching : productMatchingList) {
            Integer productId = productMatching.getProductId();
            ProductActivityExample productActivityExample = new ProductActivityExample();
            productActivityExample.createCriteria()
                    .andProductIdEqualTo(productId);
            List<ProductActivity> productActivityList = productActivityMapper.selectByExample(productActivityExample);
            ProductActivity productActivity = null;
            ProductActivityMatching productActivityMatching = new ProductActivityMatching();
            if (productActivityList.size() > 0) {
                productActivity = productActivityList.get(0);
                productActivityMatching.setProductId(productActivity.getProductId());
                productActivityMatching.setSex(productMatching.getSex());
                productActivityMatching.setComsumerPower(productMatching.getComsumerPower());
                productActivityMatching.setAgeStr(productMatching.getAgeStr());
                productActivityMatching.setProvinceJson(productMatching.getProvinceJson());
                productActivityMatching.setLabelJson(productMatching.getLabelJson());
                productActivityMatching.setCreateTime(productMatching.getCreateTime());
                productActivityMatching.setUpdateTime(productMatching.getUpdateTime());
                productActivityMatchingMapper.insertSelective(productActivityMatching);
            }
        }
    }

    public static void main(String[] args) {
        BigDecimal bigDecimal = new BigDecimal(0.8976590);
        System.out.println(bigDecimal.setScale(4, BigDecimal.ROUND_DOWN));
    }
}
